package com.itheima.health.controller;

import com.itheima.health.common.MessageConst;
import com.itheima.health.entity.Result;
import com.itheima.health.service.ReportService;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Author: liangWeiQUQ
 * @Description: 获取会员统计数据
 * @DateTime: 2021/3/8 17:16
 **/
@RequestMapping("report")
@RestController
@Slf4j
public class ReportController {
    @DubboReference
    private ReportService reportService;

    /**
     * @Author: 传闻中的梁大侠
     * @Date: 17:23 2021/3/8
     * @Parms []
     * @ReturnType: com.itheima.health.entity.Result
     * @Description: 获取会员数据统计
     */

    @GetMapping("getMemberReport")
    public Result getMemberReport() {
        Map<String, Object> resultMap = new HashMap<>();
        //组装最近十二个月的日期数据
        List<String> months = new ArrayList<>();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy.MM");
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.MONTH, -13);
        for (int i = 0; i < 12; i++) {
            instance.add(Calendar.MONTH, 1);
            String month = dateFormat.format(instance.getTime());
            months.add(month);
        }
        resultMap.put("months", months);
        //查询最近12个月的会员统计数据
        List<Integer> memberCount = reportService.getMemberReport(months);
        resultMap.put("memberCount", memberCount);
        return new Result(true, MessageConst.GET_MEMBER_NUMBER_REPORT_SUCCESS, resultMap);
    }

    /**
     * @Author: 传闻中的梁大侠
     * @Date: 11:24 2021/3/9
     * @Parms []
     * @ReturnType: com.itheima.health.entity.Result
     * @Description: 查看套餐统计数据
     */
    @GetMapping("getSetmealReport")
    public Result getSetmealReport() {
        Map<String, Object> resultMap = reportService.getSetmealReport();
        return new Result(true, MessageConst.GET_SETMEAL_COUNT_REPORT_SUCCESS, resultMap);
    }

    /**
     * @Author: 传闻中的梁大侠
     * @Date: 11:48 2021/3/9
     * @Parms []
     * @ReturnType: com.itheima.health.entity.Result
     * @Description: 会员统计
     */
    @GetMapping("getBusinessReportData")
    public Result getBusinessReportData() {
        Map<String, Object> resultMap = reportService.getBusinessReportData();
        return new Result(true, MessageConst.GET_BUSINESS_REPORT_SUCCESS, resultMap);
    }
        /**
           * @Author: 传闻中的梁大侠
           * @Date: 16:54 2021/3/9
           * @Parms [response]
           * @ReturnType: com.itheima.health.entity.Result
           * @Description: excel导出相关数据
         */

    @GetMapping("exportBusinessReport")
    public Result exportBusinessReport(HttpServletResponse response) {
        /**
         * @Author: 传闻中的梁大侠
         * @Date: 16:10 2021/3/9
         * @Parms [response]
         * @ReturnType: com.itheima.health.entity.Result
         * @Description: 获取相关数据
         */

        log.info("[导出运营数据报表]开始");
        //1.调用service获取统计的数据
        Map<String, Object> reportData = reportService.getBusinessReportData();
        log.debug("[导出运营数据报表]rpc rsp:{}", reportData);
        //2.获取报表的日期
        String reportDate = (String) reportData.get("reportDate");
        // 3.获取会员相关数据
        Long todayNewMember = (Long) reportData.get("todayNewMember");
        Long thisWeekNewMember = (Long) reportData.get("thisWeekNewMember");
        Long thisMonthNewMember = (Long) reportData.get("thisMonthNewMember");
        Integer totalMember = (Integer) reportData.get("totalMember");
        // 获取预约相关数据
        Integer todayOrderNumber = (Integer) reportData.get("todayOrderNumber");
        Integer thisWeekOrderNumber = (Integer) reportData.get("thisWeekOrderNumber");
        Integer thisMonthOrderNumber = (Integer) reportData.get("thisMonthOrderNumber");
        // 4.获取到诊相关数据
        Integer todayVisitsNumber = (Integer) reportData.get("todayVisitsNumber");
        Integer thisWeekVisitsNumber = (Integer) reportData.get("thisWeekVisitsNumber");
        Integer thisMonthVisitsNumber = (Integer) reportData.get("thisMonthVisitsNumber");
        // 5.获取套餐数据
        List<Map> hotSetmeal = (List<Map>) reportData.get("hotSetmeal");
        /**
         * @Author: 传闻中的梁大侠
         * @Date: 16:10 2021/3/9
         * @Parms [response]
         * @ReturnType: com.itheima.health.entity.Result
         * @Description: 读取构造模板
         */
        //1.构建Workbook对象，获取相关工作表
        try (InputStream is = this.getClass().getClassLoader().getResourceAsStream("report_template.xlsx");
             Workbook workbook = new XSSFWorkbook(is);
             OutputStream os = response.getOutputStream()) {
            Sheet sheet = workbook.getSheetAt(0);
            //3-填入数据
            //日期
            sheet.getRow(2).getCell(5).setCellValue(reportDate);
            //会员统计数据
            sheet.getRow(4).getCell(5).setCellValue(todayNewMember);
            sheet.getRow(4).getCell(7).setCellValue(totalMember);
            sheet.getRow(5).getCell(5).setCellValue(thisWeekNewMember);
            sheet.getRow(5).getCell(7).setCellValue(thisMonthNewMember);
            //预约到诊数据统计
            sheet.getRow(7).getCell(5).setCellValue(todayOrderNumber);
            sheet.getRow(7).getCell(7).setCellValue(todayVisitsNumber);
            sheet.getRow(8).getCell(5).setCellValue(thisWeekOrderNumber);
            sheet.getRow(8).getCell(7).setCellValue(thisWeekVisitsNumber);
            sheet.getRow(9).getCell(5).setCellValue(thisMonthOrderNumber);
            sheet.getRow(9).getCell(7).setCellValue(thisMonthVisitsNumber);
            //热门套餐
            int rowNum = 12;
            for (Map setMeal : hotSetmeal) {
                Row row = sheet.getRow(rowNum);
                row.getCell(4).setCellValue((String) setMeal.get("name"));
                row.getCell(5).setCellValue((Long) setMeal.get("setmeal_count"));
                row.getCell(6).setCellValue(((BigDecimal) setMeal.get("proportion")).doubleValue());
                rowNum++;
            }

            //4-写入网络输出流
            //写入返回流
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("content-Disposition", "attachment;fileName=" + reportDate + "_report.xlsx");
            workbook.write(os);
            return null;
        } catch (IOException e) {
            log.error("", e);
            return new Result(false, MessageConst.ACTION_FAIL);

        }
    }
}
